import IResVO from '@/model/vo/common/IResVO'
import { ToastSuccess } from '@/util/CommonUtil'
import { Form, Modal } from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { AxiosResponse } from 'axios'
import { Dispatch, SetStateAction, useRef, useState } from 'react'

interface ICInputModal {
  inputModalVisible: boolean
  setInputModalVisible: Dispatch<SetStateAction<boolean>>
  getTableData: () => void
  api: (form: ICInputModalForm) => Promise<AxiosResponse<IResVO<string>, any>>
  title: string
  label: string
}

export interface ICInputModalForm {
  inputValue?: string
}

export default function CInputModal(props: ICInputModal) {
  const formApi = useRef<FormApi>()
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态

  return (
    <Modal
      title={props.title}
      visible={props.inputModalVisible}
      onOk={() => {
        formApi.current?.submitForm()
      }}
      onCancel={() => {
        props.setInputModalVisible(false)
      }}
      maskClosable={false}
      confirmLoading={confirmLoading}
    >
      <Form
        disabled={confirmLoading}
        onSubmit={(form) => {
          if (confirmLoading) return
          setConfirmLoading(true)
          props
            .api(form as ICInputModalForm)
            .then(({ data }) => {
              ToastSuccess(data.msg)
              props.getTableData()
              setConfirmLoading(false)
              props.setInputModalVisible(false)
            })
            .catch(() => {
              setConfirmLoading(false)
            })
        }}
        getFormApi={(api) => (formApi.current = api)}
      >
        <Form.Input
          field="inputValue"
          rules={[
            {
              required: true,
              message: `请输入${props.label}`,
            },
          ]}
          showClear
          label={props.label}
        />
      </Form>
    </Modal>
  )
}
